﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace JsonSampleForYL
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.BackgroundColor = ConsoleColor.Black;
            Console.ForegroundColor = ConsoleColor.DarkGreen;

            //  将object转为Json字符串
            User user = new User("YL123", "hehehehe");
            string jsonStr = JsonConvert.SerializeObject(user);
            Console.WriteLine(jsonStr);

            //  将json转为object
            User userFromJson = JsonConvert.DeserializeObject<User>(jsonStr);
            Console.WriteLine(userFromJson);

            //  使用JsonObject来获取属性值
            JObject jsonObject = JObject.Parse(jsonStr);
            Console.Write("user name: " + jsonObject.Property("UserName").ToString());

            Console.ReadKey();
        }

        class User
        {
            private string userName;
            private string userPassword;

            public User()
            {
            }

            public User(string userName, string userPassword)
            {
                this.userName = userName;
                this.userPassword = userPassword;
            }

            public string UserName
            {
                get { return userName; }
                set { userName = value; }
            }

            public string UserPassword
            {
                get { return userPassword; }
                set { userPassword = value; }
            }

            public override string ToString()
            {
                return string.Format("user name: " + userName + ", user password: " + userPassword);
            }
        }
    }
}
